﻿@page "/history"
@inherits AuthRedirect
@inject NavigationManager NavigationManager
@inject IHttpClientFactory HttpClientFactory
@inject AuthenticationStateService AuthenticationStateService
@inject IJSRuntime JSRuntime
@using System.Text.Json.Serialization;
@using System.Text.Json;
@using System.Text;


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<div class="history-container">
    <!-- 顶部导航栏 -->
    <header class="app-header">
        <div class="logo">
            <img src="/logo.png" alt="Logo" class="logo-image">
        </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
        <div class="card history-card">
            <div class="card-header">
                <i class="bi bi-clock" style="color: #4caf50; font-size: 18px;"></i>
                <span class="section-title">历史记录</span>
                <button type="button" class="btn btn-link back-btn" @onclick="GoBack">
                    <i class="bi bi-arrow-left"></i>
                    <span>返回</span>
                </button>
            </div>
            <div class="card-body">
                @if (loading)
                {
                    <div class="text-center py-4">
                        <div class="spinner-border text-success" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">加载中...</p>
                    </div>
                }
                else if (!historyRecords.Any())
                {
                    <div class="text-center py-4">
                        <i class="bi bi-inbox" style="font-size: 48px; color: #dcdfe6;"></i>
                        <p>暂无历史记录</p>
                    </div>
                }
                else
                {
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="width: 120px;">识别ID</th>
                                    <th style="width: 180px;">识别时间</th>
                                    <th>识别类型</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var record in historyRecords)
                                {
                                    <tr @onclick="() => ShowDetails(record)">
                                        <td>@record.DetectionId</td>
                                        <td>@record.DetectionTime</td>
                                        <td>
                                            <span class="badge @GetBadgeClass(record.FeatureId)">
                                                @record.FeatureName
                                            </span>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                }
            </div>
        </div>
    </main>

    <!-- 详情弹窗 -->
    <div class="modal @(showDetailModal ? "show d-block" : "d-none")" tabindex="-1" style="background-color: rgba(0,0,0,0.5);">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">识别详情</h5>
                    <button type="button" class="btn-close" @onclick="CloseDetailModal"></button>
                </div>
                <div class="modal-body">
                    @if (selectedRecord != null)
                    {
                        <div class="result-content">
                            <div class="row">
                                <!-- 图片区域 -->
                                <div class="col-md-8">
                                    <div class="card image-card mb-3">
                                        <div class="card-header">
                                            <i class="bi bi-image" style="color: #4caf50; font-size: 18px;"></i>
                                            <span>识别结果图</span>
                                        </div>
                                        <div class="card-body">
                                            <div class="image-container">
                                                @if (!string.IsNullOrEmpty(selectedRecord?.DetectionMainResult?.ResultImage))
                                                {
                                                    <img src="data:image/jpeg;base64,@selectedRecord.DetectionMainResult.ResultImage"
                                                         class="result-image" />
                                                }
                                                else
                                                {
                                                    <div class="no-image-placeholder">
                                                        <i class="bi bi-image"></i>
                                                        <span>暂无结果图片</span>
                                                    </div>
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 信息区域 -->
                                <div class="col-md-4">
                                    <div class="card info-card mb-3">
                                        <div class="card-header">
                                            <i class="bi bi-info-circle" style="color: #4caf50; font-size: 18px;"></i>
                                            <span>识别信息</span>
                                            @if (selectedRecord?.DetectionDetails?.Count > 1)
                                            {
                                                <div class="result-switcher">
                                                    <button class="btn btn-sm btn-outline-secondary"
                                                            disabled="@(currentDetailIndex == 0)"
                                                            @onclick="() => SwitchDetail(-1)">
                                                        <i class="bi bi-arrow-left"></i>
                                                    </button>
                                                    <span class="result-counter">
                                                        @(currentDetailIndex + 1)/@selectedRecord.DetectionDetails.Count
                                                    </span>
                                                    <button class="btn btn-sm btn-outline-secondary"
                                                            disabled="@(currentDetailIndex == selectedRecord.DetectionDetails.Count - 1)"
                                                            @onclick="() => SwitchDetail(1)">
                                                        <i class="bi bi-arrow-right"></i>
                                                    </button>
                                                </div>
                                            }
                                        </div>
                                        <div class="card-body">
                                            <dl class="row">
                                                <dt class="col-sm-4">识别ID</dt>
                                                <dd class="col-sm-8">@selectedRecord?.DetectionMainResult?.DetectionId</dd>

                                                <dt class="col-sm-4">识别时间</dt>
                                                <dd class="col-sm-8">@selectedRecord?.DetectionMainResult?.DetectionTime</dd>

                                                <dt class="col-sm-4">识别结果</dt>
                                                <dd class="col-sm-8">
                                                    <span class="badge @GetBadgeClass(CurrentDetail?.ResultValue?.Name)">
                                                        @(CurrentDetail?.ResultValue?.Name ?? "未知")
                                                    </span>
                                                </dd>

                                                <dt class="col-sm-4">置信度</dt>
                                                <dd class="col-sm-8">
                                                    <span class="badge bg-success">
                                                        @Math.Round((CurrentDetail?.Confidence ?? 0) * 100)%
                                                    </span>
                                                </dd>

                                                <dt class="col-sm-4">识别类型</dt>
                                                <dd class="col-sm-8">
                                                    <span class="badge @GetBadgeClass(selectedRecord?.DetectionMainResult?.Feature?.FeatureId)">
                                                        @selectedRecord?.DetectionMainResult?.Feature?.FeatureName
                                                    </span>
                                                </dd>
                                            </dl>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 建议区域 -->
                            <div class="card advice-card">
                                <div class="card-header">
                                    <i class="bi bi-chat-left-text" style="color: #4caf50; font-size: 18px;"></i>
                                    <span>识别建议</span>
                                </div>
                                <div class="card-body">
                                    @if (!string.IsNullOrEmpty(CurrentDetail.Notes))
                                    {
                                        <div class="advice-content">
                                            @CurrentDetail.Notes
                                        </div>
                                    }
                                    else
                                    {
                                        <div class="text-center py-3">
                                            <i class="bi bi-info-circle" style="font-size: 48px; color: #dcdfe6;"></i>
                                            <p>暂无相关建议</p>
                                        </div>
                                    }
                                </div>
                            </div>
                        </div>
                    }
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="CloseDetailModal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部导航栏 -->
    <footer class="bottom-nav">
        <div class="nav-menu">
            <div class="nav-item @(activeIndex == "/home" ? "active" : "")" @onclick="@(() => HandleMenuSelect("/home"))">
                <i class="bi bi-house-door"></i>
                <span>首页</span>
            </div>
            <div class="nav-item @(activeIndex == "/detection" ? "active" : "")" @onclick="@(() => HandleMenuSelect("/detection"))">
                <i class="bi bi-camera"></i>
                <span>识别</span>
            </div>
            <div class="nav-item @(activeIndex == "/gallery" ? "active" : "")" @onclick="@(() => HandleMenuSelect("/gallery"))">
                <i class="bi bi-journal-bookmark"></i>
                <span>图鉴</span>
            </div>
        </div>
    </footer>
</div>

@code {
    private bool showDetailModal = false;
    private DetectionResult selectedRecord;
    private int currentDetailIndex = 0;
    private List<DetectionRecord> historyRecords = new();
    private bool loading = false;
    private string activeIndex = "/history";

    private DetectionDetail CurrentDetail => 
        selectedRecord?.DetectionDetails?.Count > currentDetailIndex 
            ? selectedRecord.DetectionDetails[currentDetailIndex] 
            : new DetectionDetail();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await FetchHistoryRecords();
        }
    }

    private string GetBadgeClass(object featureId)
    {
        return featureId switch
        {
            1 => "bg-primary",    // 种子质量
            2 => "bg-warning",    // 生长阶段
            3 => "bg-success",    // 叶片疾病
            4 => "bg-danger",     // 果实成熟度
            _ => "bg-info"
        };
    }

    private async Task FetchHistoryRecords()
    {
        loading = true;

        try
        {
            var userId = await GetCurrentUserId();

            var httpClient = HttpClientFactory.CreateClient("DetectionApi");

            // 获取 token 并设置请求头
            var token = await AuthenticationStateService.GetTokenAsync();
            httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue(token);

            // 调用API获取历史记录
            var response = await httpClient.GetAsync($"/api/detection/history/list?user_id={userId}");

            var ResponseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"history list API 返回: {ResponseContent}");

            if (response.IsSuccessStatusCode)
            {
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<DetectionRecord>>>();
                if (apiResponse?.Success == true)
                {
                    historyRecords = apiResponse.Data;
                }
                else
                {
                    Console.WriteLine("获取历史记录失败");
                }
            }
            else
            {
                Console.WriteLine($"HTTP错误: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取历史记录失败: {ex.Message}");
        }
        finally
        {
            loading = false;
            StateHasChanged();
        }
    }

    private async Task ShowDetails(DetectionRecord record)
    {
        loading = true;

        try
        {
            var httpClient = HttpClientFactory.CreateClient("DetectionApi");

            // 获取 token 并设置请求头
            var token = await AuthenticationStateService.GetTokenAsync();
            httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue(token);

            // 调用API获取详细信息
            var response = await httpClient.GetAsync($"/api/detection/history/detail?detection_id={record.DetectionId}");

            if (response.IsSuccessStatusCode)
            {
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<DetectionResult>>();
                if (apiResponse?.Success == true)
                {
                    selectedRecord = new DetectionResult
                        {
                            DetectionMainResult = apiResponse.Data.DetectionMainResult,
                            DetectionDetails = apiResponse.Data.DetectionDetails
                        };

                    currentDetailIndex = 0;
                    showDetailModal = true;
                }
                else
                {
                    Console.WriteLine("获取详情失败");
                }
            }
            else
            {
                Console.WriteLine($"HTTP错误: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取详情失败: {ex.Message}");
        }
        finally
        {
            loading = false;
            StateHasChanged();
        }
    }

    private void CloseDetailModal()
    {
        showDetailModal = false;
    }

    private void SwitchDetail(int step)
    {
        var newIndex = currentDetailIndex + step;
        if (newIndex >= 0 && newIndex < selectedRecord.DetectionDetails.Count)
        {
            currentDetailIndex = newIndex;
            StateHasChanged();
        }
    }

    private void GoBack()
    {
        NavigationManager.NavigateTo("/home");
    }

    private void HandleMenuSelect(string index)
    {
        activeIndex = index;
        NavigationManager.NavigateTo(index);
    }

    // 数据模型类
    public class TokenResponse
    {
        public string Expires_at { get; set; }
        public string Token { get; set; }
    }

    public class DetectionRecord
    {
        [JsonPropertyName("detection_id")]
        public int DetectionId { get; set; }

        [JsonPropertyName("feature_id")]
        public int FeatureId { get; set; }

        [JsonPropertyName("feature_name")]
        public string FeatureName { get; set; }

        [JsonPropertyName("detection_time")]
        public string DetectionTime { get; set; }
    }

    public class DetectionResult
    {
        [JsonPropertyName("detection_result")]
        public DetectionMainResult DetectionMainResult { get; set; }

        [JsonPropertyName("detection_details")]
        public List<DetectionDetail> DetectionDetails { get; set; } = new();
    }

    public class DetectionMainResult
    {
        [JsonPropertyName("detection_id")]
        public int DetectionId { get; set; }

        [JsonPropertyName("image_64")]
        public string ImageBase64 { get; set; }

        public Feature Feature { get; set; }

        [JsonPropertyName("detection_time")]
        public string DetectionTime { get; set; }

        [JsonPropertyName("result_image")]
        public string ResultImage { get; set; }
    }

    public class Feature
    {
        [JsonPropertyName("feature_id")]
        public int FeatureId { get; set; }

        [JsonPropertyName("feature_name")]
        public string FeatureName { get; set; }
    }

    public class DetectionDetail
    {
        [JsonPropertyName("result_type")]
        public string ResultType { get; set; }

        [JsonPropertyName("result_value")]
        public ResultValue ResultValue { get; set; }

        public decimal? Confidence { get; set; }

        public string Notes { get; set; }
    }

    public class ResultValue
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    public class ApiResponse<T>
    {
        public bool Success { get; set; }

        public string Message { get; set; }

        public T Data { get; set; }
    }

    private async Task<string> GetCurrentUserId()
    {
        var user_id = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "userId");
        return user_id;
    }
}

<style>
    .history-container {
        height: 100vh;
        display: flex;
        flex-direction: column;
        background-color: #f8faf8;
        font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }

    /* 顶部导航栏 */
    .app-header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1000;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
        height: 60px;
        background-color: white;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .logo-image {
        height: 40px;
        border-radius: 40px;
    }

    /* 主要内容区域 */
    .main-content {
        flex: 1;
        padding: 80px 15px 70px;
        overflow-y: auto;
        max-width: 1200px;
        margin: 0 auto;
        width: 100%;
    }

    /* 卡片样式 */
    .history-card {
        margin-bottom: 20px;
        border-radius: 12px;
        border: none;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    /* 分区标题 */
    .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        position: relative;
        background-color: white;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        padding: 15px 20px;
        border-radius: 12px 12px 0 0 !important;
    }

    .section-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
    }

    /* 返回按钮 */
    .back-btn {
        position: absolute;
        right: 15px;
        color: #4caf50;
        text-decoration: none;
        display: flex;
        align-items: center;
        gap: 5px;
        background: none;
        border: none;
        padding: 5px 10px;
        border-radius: 20px;
        transition: background-color 0.3s;
    }

        .back-btn:hover {
            background-color: rgba(76, 175, 80, 0.1);
        }

    /* 表格样式 */
    .table {
        width: 100%;
        margin-bottom: 1rem;
        color: #212529;
        border-collapse: collapse;
    }

    .table-hover tbody tr:hover {
        background-color: rgba(0, 0, 0, 0.075);
        cursor: pointer;
    }

    /* 详情弹窗样式 */
    .modal {
        background-color: rgba(0,0,0,0.5);
    }

    .modal-dialog {
        max-width: 90%;
        margin: 1.75rem auto;
    }

    .modal-content {
        border: none;
        border-radius: 12px;
        overflow: hidden;
    }

    .modal-header {
        border-bottom: 1px solid rgba(0,0,0,0.05);
        padding: 15px 20px;
    }

    .modal-title {
        font-size: 16px;
        font-weight: bold;
    }

    .modal-body {
        padding: 20px;
    }

    .modal-footer {
        border-top: 1px solid rgba(0,0,0,0.05);
        padding: 15px 20px;
    }

    /* 图片区域 */
    .image-card {
        margin-bottom: 20px;
        border-radius: 10px;
        border: none;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .image-container {
        width: 100%;
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f5f7fa;
        border-radius: 8px;
        overflow: hidden;
    }

    .result-image {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }
    /* 信息区域 */
    .info-card {
        margin-bottom: 20px;
        border-radius: 10px;
        border: none;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }
    /* 结果切换器 */
    .result-switcher {
        position: absolute;
        right: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .result-counter {
        font-size: 14px;
        color: #666;
    }
    /* 建议区域 */
    .advice-card {
        border-radius: 10px;
        border: none;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .advice-content {
        padding: 10px;
        color: #666;
        white-space: pre-line;
        line-height: 1.6;
    }
    /* 底部导航栏 */
    .bottom-nav {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 60px;
        background-color: white;
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
        z-index: 100;
    }

    .nav-menu {
        display: flex;
        height: 100%;
    }

    .nav-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #757575;
        cursor: pointer;
        transition: all 0.3s;
    }

        .nav-item i {
            font-size: 22px;
            margin-bottom: 4px;
        }

        .nav-item span {
            font-size: 12px;
        }

        .nav-item.active {
            color: #4caf50;
        }

        .nav-item:hover {
            color: #2e7d32;
        }
</style>